package com.jieshuibao.controller.wx;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.controller.GenericController;
import com.jieshuibao.service.CoreService;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.wx.util.ReturnModel;


/**
 * @author :liuxb@jieshuibao.com
 * @version ：2018年9月3日 下午3:56:56
 * 类说明
 */
@Controller
@RequestMapping("/wx")
public class WxCoreController extends GenericController{
	
	@Resource
    protected WxMpConfigStorage wxMpConfigStorage;
	@Autowired
    protected WxMpService wxMpService;
	@Autowired
	protected CoreService coreService;

	
	  /**
     * 微信公众号webservice主服务接口，提供与微信服务器的信息交互
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/core")
    public void wechatCore(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        	//WxMpMessageRouter router = new WxMpMessageRouter(wxMpService);
        	
        if (!this.wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            response.getWriter().println("非法请求");
            return;
        }

        String echoStr = request.getParameter("echostr");
        if (StringUtils.isNotBlank(echoStr)) {
            // 说明是一个仅仅用来验证的请求，回显echostr
            String echoStrOut = String.copyValueOf(echoStr.toCharArray());
            response.getWriter().println(echoStrOut);
            return;
        }

        String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type"))
            ? "raw"
            : request.getParameter("encrypt_type");

        if ("raw".equals(encryptType)) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
           // WxMpXmlOutMessage outMessage = router.route(inMessage);
            System.out.println("\n内容为：\n{}"+inMessage.toString());
            WxMpXmlOutMessage outMessage = this.coreService.route(inMessage);
            response.getWriter().write(outMessage.toXml());
           // WxMpXmlOutMessage outMessage = this.coreService.route(inMessage);
           // response.getWriter().write(outMessage.toXml());
           // response.getWriter().write("<xml> <ToUserName>< ![CDATA[o64YVv33vO1eNi0LYFtU1Sp5tsdE] ]></ToUserName> <FromUserName>< ![CDATA[gh_03cc526f4d0c] ]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[你好] ]></Content> </xml>");
            return;
        }

        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            String msgSignature = request.getParameter("msg_signature");
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
                request.getInputStream(), this.wxMpConfigStorage, timestamp, nonce,
                msgSignature);
            System.out.println("\n消息解密后内容为：\n{}"+inMessage.toString());
            
           // this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            //WxMpXmlOutMessage outMessage = router.route(inMessage);
            WxMpXmlOutMessage outMessage = this.coreService.route(inMessage);
           // this.logger.info(response.toString());
            response.getWriter()
                .write(outMessage.toEncryptedXml(this.wxMpConfigStorage));
            return;
        }

        response.getWriter().println("不可识别的加密类型");
        return;
    }

    /**
     * 用code换取oauth2的openid
     * 详情请见: http://mp.weixin.qq.com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html
     *
     * @param response
     * @param code     code
     */
    @RequestMapping(value = "/getOpenid/{code}",method=RequestMethod.POST)
    @ResponseBody
    public Object getOpenid(HttpServletResponse response, @PathVariable String code) {
    	BaseRes<String> res = new BaseRes<String>();
    	
        WxMpOAuth2AccessToken accessToken;
        try {
        	logger.info("接收到的code:"+code);
        	if (StringUtils.isBlank(code)) {
        		res.setCode(BaseRes.ERRORPARAM_CODE);
            	res.setDes(BaseRes.ERRORPARAM_DES);
            	return res;	
			}
            accessToken = this.wxMpService.oauth2getAccessToken(code);
            if(null == accessToken){
            	res.setCode(BaseRes.FAIL_CODE);
            	res.setDes("获取失败");
            	return res;
            }
            System.out.println(JsonUtil.toJson("===================="+accessToken.getOpenId())+"=======================");
            res.setCode(BaseRes.SUCCESS_CODE);
            res.setData(accessToken.getOpenId());
            res.setDes("获取成功");
            return res;
        } catch (WxErrorException e) {
        	this.logger.error(e.getError().toString());
            res.setCode(BaseRes.FAIL_CODE);
        	res.setDes(e.getError().toString());
        	return res;
        }
    }
    @RequestMapping(value = "/createJsapiSignature")
	public void createJsapiSignature(HttpServletResponse response,@RequestParam String url) {
		ReturnModel returnModel = new ReturnModel();
		try {
//			if(StringUtils.contains(url, "#")){
//				url = url.substring(0, url.indexOf("#"));
//			}
			System.out.println(url);
			WxJsapiSignature createJsapiSignature = this.wxMpService.createJsapiSignature(url);
			returnModel.setResult(true);
			returnModel.setDatum(createJsapiSignature);
			System.out.println(JsonUtil.toJson(returnModel));
			renderString(response, returnModel);
		} catch (WxErrorException e) {
			returnModel.setResult(false);
			returnModel.setReason(e.getError().toString());
			renderString(response, returnModel);
			this.logger.error(e.getError().toString());
		}
	}
}
